package tutorial.multicast;

import java.io.File;
import java.io.IOException;
import java.net.DatagramPacket;
import java.util.Date;

import net.jxta.peergroup.PeerGroup;
import net.jxta.platform.NetworkManager;
import net.jxta.socket.JxtaMulticastSocket;

/**
 * Simple example to illustrate the use of JxtaMulticastSocket
 */
public class JxtaMulticastSocketClient {
	/**
	 * main
	 * 
	 * @param args
	 *            command line args
	 */
	public static void main(String args[]) {
		NetworkManager manager = null;
		try {
			manager = new net.jxta.platform.NetworkManager(
					NetworkManager.ConfigMode.EDGE,
					"JxtaMulticastSocketClient", new File(new File(".cache"),
							"JxtaMulticastSocketClient").toURI());
			manager.startNetwork();
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(-1);
		}
		PeerGroup netPeerGroup = manager.getNetPeerGroup();
		JxtaMulticastSocket mcastSocket = null;
		try {
			mcastSocket = new JxtaMulticastSocket(netPeerGroup,
					JxtaMulticastSocketServer.getSocketAdvertisement());
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(-1);
		}
		Date date = new Date(System.currentTimeMillis());
		String hello = "Hello on : " + date.toString();
		try {
			DatagramPacket packet = new DatagramPacket(hello.getBytes(), hello
					.length());
			mcastSocket.setLoopbackMode(true); //disable loopback
			mcastSocket.send(packet);
			//byte[] res = new byte[16384];
			byte[] res = new byte[163840033];
			DatagramPacket rpacket = new DatagramPacket(res, res.length);
			// It's likely we'll receive 2 packets a loopback and a response
			// loopback
			//mcastSocket.receive(rpacket);
			// server response
//			mcastSocket.receive(rpacket);
//			String sw = new String(rpacket.getData(), 0, rpacket.getLength());
//			System.out.println("Received data from :" + rpacket.getAddress());
//			System.out.println(sw);
			// stop the platform
			mcastSocket.disconnect();
			mcastSocket.close();
			manager.stopNetwork();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
